#encoding: utf-8

=begin

优惠券结算订单绑定程序，在update-tags.rb中周期调用

所有使用过的优惠券，如果已使用未结算（status==1 and due_oid==0），即eb_store_coupon_user.due_oid==0，则：

1）如该券为品类券或者通用券，due_oid记为999999999并结束；否则该券为产品券，进入2）
2）找出适用的产品pids，如不归属同一商家，due_oid记为999999999并结束；否则该券可归于单一商家，进入3）
3）找出使用过该券的所有订单oids，找到第一张含有pids中任一pid的订单oid，进入4）
4）将due_oid记为oid，将eb_store_order中的coupon_due记为coupon_user中的coupon_price,due_oid记为oid

=end

load 'rds_api.rb'

# 获得所有未绑定结算订单的用户优惠券
def get_unbinded_coupons
  coupons = []
  sql = "select u.*, c.type as ctype, c.product_id as pids from crmeb.eb_store_coupon_user u 
      left join crmeb.eb_store_coupon c on (u.cid=c.id)
      where u.status = 1 and u.due_oid = 0"
  queryRds(sql).each { |q| coupons += [q] }
  return coupons
end

def mark_as_category coupon
  sql = "update crmeb.eb_store_coupon_user set due_oid=999999999 where id = #{coupon['id']}"
  queryRds sql
end

def mark_as_general coupon
  sql = "update crmeb.eb_store_coupon_user set due_oid=999999999 where id = #{coupon['id']}"
  queryRds sql
end

def mark_as_multiple coupon
  sql = "update crmeb.eb_store_coupon_user set due_oid=999999999 where id = #{coupon['id']}"
  queryRds sql
end

def get_mers coupon
  pids = coupon['pids'].split(',')
  merHash = {}
  sql = "select mer_id from crmeb.eb_store_product where id in (#{coupon['pids']});"
  queryRds(sql).each { |q| merHash.store(q['mer_id'],true) }
  return merHash
end

def bind_to_order mer_id, coupon
  sql = "select id from crmeb.eb_store_order where mer_id = #{mer_id} and coupon_id = #{coupon['id']} limit 1;"
  queryRds(sql).each do |q|
    order_id = q['id']
    usqls = []
    usqls += ["update crmeb.eb_store_order set coupon_due = #{coupon['coupon_price']}, coupon_due_comment = '#{coupon['id']}##{coupon['coupon_title']}' where id = #{order_id};"]
    usqls += ["update crmeb.eb_store_coupon_user set due_oid=#{order_id} where id = #{coupon['id']}"]
    commitTrans usqls
    break
  end
end

def mark_order_for_coupons coupons
  coupons.each do |coupon|
    case coupon['ctype']
    when 0 #通用
      mark_as_category coupon
    when 1 #品类
      mark_as_general coupon
    when 2 #商品
      merHash = get_mers coupon
      if merHash.size == 1 #
        mer_id = merHash.first[0]
        bind_to_order mer_id, coupon
      else
        mark_as_multiple coupon
      end
    else
      puts "ERROR: untracked ctype for #{coupon['id']}"
      exit
    end
  end
end

coupons = get_unbinded_coupons
mark_order_for_coupons coupons
puts "done. #{coupons.size}"
